package be.dataflow.xtime;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import be.dataflow.xtime.DFHttpClient.ApiException;

public class OnAlarmReceiver extends BroadcastReceiver { 
	@Override
	public void onReceive(Context context, Intent intent) {
		// Let's poll for data
		try {
			JSONObject json = DFHttpClient.getJSON(XtimeActivity.baseurl+"message");
			String newmessage = json.toString();
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			String lastmessage = prefs.getString("lastmessage", null);
			
			if (!newmessage.equals(lastmessage)) {
				// Set up a notification
				NotificationManager mgr=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
				Notification note=new Notification(R.drawable.ic_launcher, "X-Time", System.currentTimeMillis()); 
				PendingIntent i=PendingIntent.getActivity(context, 0, new Intent(context, XtimeActivity.class), 0);
				note.setLatestEventInfo(context, "X-Time", json.getString("nickname") + " says: "+json.getString("message"), i);
				note.flags|=Notification.FLAG_AUTO_CANCEL;
				mgr.notify(9876, note);
				
				// Saving last message in preferences
				prefs.edit().putString("lastmessage", newmessage).commit();
			}
			
		} catch (ApiException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}